<script setup lang="ts">
import {
  ElRow,
  ElCol,
  ElInput,
  ElButton,
  ElCheckbox,
  ElMessage,
  ElMessageBox,
  ElAlert,
} from "element-plus";
import { ref, onMounted, onUnmounted, watch } from "vue";
import { DocumentEditor } from "@onlyoffice/document-editor-vue";
const scriptUrl = defineModel("scriptUrl");
const demoFileUrl = defineModel("demoFileUrl");
const demoConfigType = defineModel("demoConfigType");
const demoConfigMode = defineModel("demoConfigMode");
interface Props {
  scriptUrl?: string;
}

defineOptions({
  name: "BookmarkFormDemo",
});

const props = withDefaults(defineProps<Props>(), {});

const getUuid = function () {
  return "xxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

const VITE_ONLY_OFFICE_BASE_URL = import.meta.env.VITE_ONLY_OFFICE_BASE_URL;
const url = ref("http://47.94.91.67/demo_file/demo.docx");
const containerRef = ref();

const init = function () {
  config.value.document.key = getUuid();
  config.value.document.url = demoFileUrl.value;
  config.value.document.type = demoConfigType.value;
  config.value.editorConfig.mode = demoConfigMode.value;
  documentEditorKey.value = config.value.document.key;
};

let containerWidth = 0;
let containerHeight = 0;
let documentEditorKey = ref("");
onMounted(() => {
  containerWidth = containerRef.value.parentNode.offsetWidth;
  containerHeight = containerRef.value.parentNode.offsetHeight;
  if (containerHeight > 800) {
    containerHeight = 800;
  }
  containerRef.value.style.height = containerHeight + "px";
  documentEditorKey.value = getUuid();
  init();
});

onUnmounted(() => {});

var config = ref({
  type: "desktop",
  // "type": "mobile",
  documentType: "word",
  historyList: {
    history: [],
    currentVersion: "1",
  },
  document: {
    title: "通用模板.docx",
    // url: "https://d2nlctn12v279m.cloudfront.net/assets/docs/samples/zh/demo.docx",
    url: "",
    permissions: {
      print: true,
      download: true,
      edit: true,
    },
    fileType: "docx",
    key: getUuid(),
  },
  editorConfig: {
    customization: {
      autosave: false,
      compactToolbar: false,
      forcesave: true,
      toolbarNoTabs: true,
      help: false,
      compactHeader: false,
      hideRightMenu: true,
      plugins: true,
      uiTheme: "theme-light",
    },
    mode: "edit",
    callbackUrl:
      "https://api.docs.onlyoffice.com/dummyCallback",
    lang: "zh-CN",
    user: {
      name: "曹瑞剑雄",
      id: "104",
    },
  },
});

let currentConnector = null;
let contentItemList = ref(["title", "customer", "table_1"]);
let formData = ref({
  'title': '',
  "customer": '',
  'table_1':''
});
const onDocumentReady = () => {
  console.log("onDocumentReady");
  currentConnector = DocEditor.instances.docEditor.createConnector();
  window.connector = currentConnector;
  Asc.scope = {
      list: contentItemList.value
  };
  currentConnector.callCommand(function () {
    Api.openBookmarkMaybeChange();
      // var oDocument = Api.GetDocument();
      // for(var i=0;i<Asc.scope.list.length;i++){
      //   var name = Asc.scope.list[i];
      //   var oRange = oDocument.GetBookmarkRange(name);
      //   if(!oRange){
      //     continue;
      //   }
        // oRange.SetHighlight("yellow");
      // }
  }, function () {
    currentConnector.attachEvent('onBookmarkMaybeChange', updateBookmarm);
  });
};

let bookmarkNameExist = function (name) {
  for (var i = 0; i < contentItemList.value.length; i++) {
    if (name == contentItemList.value[i]) {
      return true;
    }
  }
  return false;
};
let deleteBookmark = function (name) {
  for (var i = 0; i < contentItemList.value.length; i++) {
    let temp = contentItemList.value[i];
    if (name == temp) {
      contentItemList.value.splice(i, 1);
      if(formData.value[name]){
        delete formData.value[name];
        
      }
      Asc.scope = {
        name: name
      };
      currentConnector.callCommand(function () {
        console.log(1111, Asc.scope.name);
        Api.RemoveBookmark(Asc.scope.name);
      }, function (resultValue) {});
      break;
    }
  }
};

let insertBookmark = function () {
  currentConnector.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      var oRange = oDocument.GetRangeBySelect();
      if (!oRange) {
        return false;
      }
      return true;
    },
    function (resultValue) {
      if (!resultValue) {
        ElMessage.error("请先选中文字");
        return;
      }
      ElMessageBox.prompt("请输入书签名", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(({ value }) => {
        if (value == undefined || "" == value) {
          ElMessage.error("请输入书签名");
          return;
        }
        if (bookmarkNameExist(value)) {
          ElMessage.error("书签名已存在，请重新输入");
          return;
        }
        Asc.scope = {
            name: value
        };
        currentConnector.callCommand(
          function () {
            var oDocument = Api.GetDocument();
            var oRange = oDocument.GetRangeBySelect();
            if (!oRange) {
              return false;
            }
            oRange.AddBookmark(Asc.scope.name);
            // oRange.SetHighlight("yellow");
            return true;
          },
          function (resultValue1) {
            if(!resultValue1){
                ElMessage.error("绑定失败");
                return;
            }
            contentItemList.value.push(value);
            formData.value[value] = '';
            ElMessage({
                message: '绑定成功',
                type: 'success',
            });
          }
        );
      });
    }
  );
};

let updateBookmarm = function (data) {
  if (typeof data != 'object') {
    return;
  }
  if(Object.keys(data).length == 0){
    return;
  }
  Asc.scope = {
    nameObj: data,
  };
  connector.callCommand(
    function () {
      var resultData = {};
      var oDocument = Api.GetDocument();
      for (var name in Asc.scope.nameObj) {
        var oRange = oDocument.GetBookmarkRange(name);
        if (!oRange) {
          continue;
        }
        resultData[name] = oRange.GetText();
      }
      return resultData;
    },
    function (resultValue) {
      for(var name in resultValue){
        if(formData.value[name] == undefined || formData.value[name] == null){
          continue;
        }
        if(formData.value[name] === resultValue[name]){
          continue;
        }
        formData.value[name] = resultValue[name];
      }
    },
  );
};

const changeText = function (bookmarkName) {
    Asc.scope = {
        name: bookmarkName,
        text: formData.value[bookmarkName]
    };
    currentConnector.callCommand(function () {
        var oDocument = Api.GetDocument();
        // var bookmark = oDocument.GetBookmark(Asc.scope.name);
        // bookmark.SetText(Asc.scope.text);
        var oRange = oDocument.GetBookmarkRange(Asc.scope.name);
        oRange.SetBookmarkText(Asc.scope.text);
        // oRange.SetHighlight("yellow");
    }, function (resultValue) {});
};
</script>

<template>
  <di class="onlyoffice_demo_container" ref="containerRef">
    <el-row style="height: 100%;overflow: scroll;">
      <el-col :span="9">
        <div
          style="
            width: 100%;
            height: 100%;
            overflow: scroll;
            background: #ffffff;
          "
        >
          <el-row class="gap_row">
            
            <el-col :span="24">
              <div class="grid-content ep-bg-purple-dark" />
              <el-alert
                style="
                  height: 60px;
                  font-size: 15px;
                  font-weight: 600;
                  margin-bottom: 15px;
                "
                title="你可以选中文字后绑定书签试试"
                type="error"
              />
              <el-alert
                style="
                  height: 60px;
                  font-size: 15px;
                  font-weight: 600;
                  margin-bottom: 15px;
                "
                title="书签Tag唯一，字段多标签绑定关系请设计关联表存储对应关系"
                type="error"
              />
              <el-alert
                style="
                  height: 60px;
                  font-size: 15px;
                  font-weight: 600;
                  margin-bottom: 15px;
                "
                title="https://blog.csdn.net/lz610756247/article/details/144610532"
                type="error"
              />
              
              <el-button type="primary" @click="insertBookmark()"
                >绑定书签</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            已存在书签：{{ contentItemList }}
            <el-col :span="24">
              <el-row class="gap_row" v-for="bookmarkName in contentItemList">
                  <el-col :span="18">
                    <el-input
                      v-model="formData[bookmarkName]"
                      placeholder="请输入文字"
                      style="width: 340px"
                      @input="changeText(bookmarkName)"
                    >
                    <template #prepend>{{ bookmarkName }}</template>
                  </el-input>
                  </el-col>
                  <el-col :span="6">
                    <el-button
                      v-if="bookmarkName != 'title' && bookmarkName != 'customer' && bookmarkName != 'table_1'"
                      type="danger"
                      @click="deleteBookmark(bookmarkName)"
                      >删除</el-button
                    >
                  </el-col>
                </el-row>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <el-col :span="15">
        <DocumentEditor
          id="docEditor"
          :documentServerUrl="VITE_ONLY_OFFICE_BASE_URL"
          :config="config"
          :events_onDocumentReady="onDocumentReady"
          height="100%"
        />
      </el-col>
    </el-row>
  </di>
</template>

<style scoped>
.onlyoffice_demo_container {
  width: 100%;
  height: 100%;
  display: inline-block;
}

.gap_row {
  margin-top: 15px;
  margin-bottom: 15px;
}

.bg-purple {
  min-height: 36px;
  line-height: 36px;
  background: #d3dce6;
}
</style>
